import json
from concurrent.futures import ThreadPoolExecutor
import threading

class pNet:
    def __init__(self,client_main ,client_fast, prompts, C2J):
        self.LLM_main_dict = {}
        self.client_main = client_main
        self.client_fast = client_fast
        self.prompts = prompts
        self.C2J = C2J
        self.thread_lock = threading.Lock()
        self.counter = 1

    def get_jsonVa(self, json_str):
        try:
            data = json.loads(json_str)
        except json.JSONDecodeError as e:
            raise ValueError("无效的JSON格式") from e

        if not isinstance(data, dict):
            raise ValueError("输入必须是JSON对象")

        values = []
        for key, value in data.items():
            if not isinstance(value, str):
                raise ValueError(f"键'{key}'的值不是字符串类型")
            values.append(value)

        return values

    def _process_single_item(self, item):
        try:
            result = self.get_shots(item)

            with self.thread_lock:
                print(1)
                self.LLM_main_dict[self.counter] = result  # 假设item有唯一标识key
                self.counter += 1
        except Exception as e:
            print(f"处理 {item} 时发生异常: {str(e)}")

    def get_first_final(self, shot):
        ffs = self.client_main.get_contex(self.prompts.ff,shot)
        ffs = self.client_fast.get_contex(self.C2J.ff, ffs)
        move = self.client_main.get_contex(self.prompts.move,shot)
        return dict(first = ffs[0],final = ffs[1], move = move)

    def get_shots(self, parda):
        shots  = self.client_main.get_contex(self.prompts.shot,parda)
        print(shots)
        shotsJ = self.client_fast.get_contex(self.C2J.shot, shots)
        tdict ={}
        tcount = 0
        for shot in shotsJ:
            tdict[tcount] = self.get_first_final(shot)

        tdict["shots"] = shotsJ
        tdict["scene"] = self.client_main.get_contex(self.prompts.scene,parda)
        return tdict

    def get_pardas(self, story):
        pardas = self.client_main.get_contex(self.prompts.parda,story)
        print(pardas)
        pardasJ = self.client_fast.get_contex(self.C2J.parda, pardas)
        with ThreadPoolExecutor(max_workers=5) as executor:
            # 将任务提交到线程池执行
            executor.map(self._process_single_item, pardasJ)

        self.LLM_main_dict['pardas'] = pardasJ
        return self.LLM_main_dict


    def update_shot(self, new_shot, locate_parda = int, locate_shot = int):
        self.LLM_main_dict[locate_parda][locate_shot] = self.get_first_final(new_shot)
        self.LLM_main_dict[locate_parda]["shots"][locate_shot] = new_shot


    def update_parda(self, new_parda, locate_parda = int):
        self.LLM_main_dict[locate_parda] = self.get_shots(new_parda)
        self.LLM_main_dict[locate_parda]["pardas"][locate_parda] = new_parda

